from sqlalchemy import create_engine, MetaData, text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import logging

class DatabaseConnector:
    def __init__(self):
        self.engine = None
        self.session_maker = None
        self.metadata = None
        self.Base = declarative_base()
        self.is_connected = False
        self.database = None
        self.logger = logging.getLogger(__name__)
    
    def connect(self, host = "localhost", port = 3306, username = "root", password = "root1234", database = "mt-com", charset='utf8mb4'):
        try:
            connection_string = f"mysql+pymysql://{username}:{password}@{host}:{port}/{database}?charset={charset}"
            self.engine = create_engine(connection_string)
            self.session_maker = sessionmaker(bind=self.engine)
            self.metadata = MetaData()
            self.metadata.reflect(bind=self.engine)
            self.database = database
            
            with self.engine.connect() as conn:
                self.is_connected = True
                return True
        except Exception as e:
            self.is_connected = False
            return False
    
    def execute_query(self, query):
        try:
            with self.engine.connect() as conn:
                stmt = text(query)
                result = conn.execute(stmt)
                rows = []
                for row in result:
                    rows.append({col: getattr(row, col) for col in row._fields})
                return rows
        except Exception as e:
            self.logger.error(f"Error executing query: {str(e)}")
            raise